package com.xhu.Interceptor;

import com.xhu.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户的认证信息
        User userInfo = (User) request.getSession().getAttribute("userInfo");
        log.debug("进入拦截器的url:"+request.getRequestURL());
        log.debug(request.getSession().getId());
        if(userInfo == null){
            this.returnJson(response);
            return false;
        }
        else{
            log.debug("没有被拦截的url:"+request.getRequestURL());
            return true;
        }
    }

    /**
     * 返回json，前后端分离
     * @param response
     */
    private void returnJson(HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print("{\"tokenError\":\"404\"}");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null) {
                writer.close();
            }
        }
    }
}
